<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRoute } from 'vue-router'
import { timeFormat_2, copyToCliboard, toYuan } from '@/hooks/util'
import * as xyApi from '@/api/xy'
import { message } from 'ant-design-vue'
import PullXyRobot from '@/components/PullRobot/PullXyRobot.vue'
import RefundModal from './components/RefundModal.vue'
import * as accountApi from '@/api/account'
import SearchDrawer from '@/components/search-drawer/Index.vue'

const searchDrawerRef = ref()

const route = useRoute()
const refundModalRef = ref()

interface Pagination {
  page: number
  pageSize: number
  total: number
  current?: number
  onChange: Function
  showSizeChanger: boolean
  showQuickJumper: boolean
}

const handlePageChange = (page: any, pageSize: any) => {
  // console.log(page, pageSize)
  pagination.value.pageSize = pageSize
  searchParams.value.pageSize = pageSize
}

const pagination = ref<Pagination>({
  page: 1,
  pageSize: 10,
  total: 0,
  onChange: handlePageChange,
  showSizeChanger: true,
  showQuickJumper: true,
})
let loading = ref<boolean>(false)

interface SearchParams {
  currentPage: number
  pageSize: number
  [propName: string]: any
}
const searchParams = ref<SearchParams>({
  currentPage: pagination.value.page,
  pageSize: pagination.value.pageSize,
})

const dataSource = ref([])
const columns = [
  {
    title: '主订单信息',
    key: 'createTime',
    width: 360,
  },
  {
    title: '宝贝信息',
    key: 'productImg',
    width: 300,
  },
  {
    title: '退款订单信息',
    key: 'orderNumber',
    width: 360,
  },
  {
    title: '买家信息',
    key: 'fansNickName',
    width: 360,
  },
  {
    title: '退款信息',
    key: 'remark',
    width: 400,
  },
  // {
  //   title: '修改时间',
  //   key: 'updateTime',
  //   width: 180,
  // },
  {
    title: '操作',
    key: 'action',
    width: 200,
    align: 'center',
    fixed: 'right',
  },
]

// 翻页
const changePage = (e: any) => {
  pagination.value.current = e.current
  pagination.value.pageSize = e.pageSize
  searchParams.value.currentPage = pagination.value.current as number
  getList()
}

const getList = async () => {
  loading.value = true
  try {
    let { state, data, message: msg } = await xyApi.fishRefundOrderList(searchParams.value)
    if (state === 200) {
      data.list.forEach((item: { isRemarkShow: boolean }) => {
        item.isRemarkShow = false
      })
      dataSource.value = data.list
      pagination.value.total = Number(data.totalCount)
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
  loading.value = false
}

import type { SelectProps } from 'ant-design-vue'
const orderStatusList = ref<SelectProps['options']>([
  {
    label: '买家已经申请退款，等待卖家同意',
    value: 1,
  },
  {
    label: '卖家已经同意退款，等待买家退货',
    value: 2,
  },
  {
    label: '买家已经退货，等待卖家确认收货',
    value: 3,
  },
  {
    label: '退款关闭',
    value: 4,
  },
  {
    label: '退款成功',
    value: 5,
  },
  {
    label: '卖家拒绝退款',
    value: 6,
  },
  {
    label: '等待卖家确认退货地址',
    value: 8,
  },
  {
    label: '没有申请退款',
    value: 9,
  },
  {
    label: '退款结束',
    value: 11,
  },
  {
    label: '未知',
    value: 0,
  },
])

const formRef = ref()
interface FormState {
  orderNumber?: string
  refundStatus?: string
  [propName: string]: any
}
const formState = reactive<FormState>({})

// 查询
const search = () => {
  pagination.value.current = 1
  searchParams.value.currentPage = 1
  formRef.value.validate().then(() => {
    searchParams.value.orderNumber = formState.orderNumber || ''
    searchParams.value.refundStatus = formState.refundStatus || ''
    searchParams.value.fansNickName = formState.fansNickName || ''
    searchParams.value.refundOrderNumber = formState.refundOrderNumber || ''
    getList()
  })
}

// 重置
const reset = () => {
  pagination.value.current = 1
  searchParams.value.currentPage = 1
  formRef.value.resetFields()

  for (let key in searchParams.value) {
    if (key != 'currentPage' && key != 'pageSize' && key != 'robotId')
      searchParams.value.hasOwnProperty(key) && delete searchParams.value[key]
  }

  getList()
}

const selectRobot = (id: string) => {
  searchParams.value.robotId = id
  getList()
}

const copyRule = (orderNumber: string) => {
  copyToCliboard(orderNumber)
}

const refundMoney = (record: any) => {
  console.log('订单退款')
  refundModalRef.value.showModal(record)
}

const nOAgree = async (orderId: string, id: string) => {
  let params = {
    orderId: orderId,
    operation: 2,
    refundOrderId: id,
  }
  try {
    const { state, message: msg } = await xyApi.orderDealRefund(params)
    if (state === 200) {
      message.success('操作成功')
      getList()
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

const okAgree = async (orderId: string, id: string) => {
  let params = {
    orderId: orderId,
    operation: 1,
    refundOrderId: id,
  }
  try {
    const { state, message: msg } = await xyApi.orderDealRefund(params)
    if (state === 200) {
      message.success('操作成功')
      getList()
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

const okAgree_2 = async (orderId: string, id: string) => {
  let params = {
    orderId: orderId,
    operation: 3,
    refundOrderId: id,
  }
  try {
    const { state, message: msg } = await xyApi.orderDealRefund(params)
    if (state === 200) {
      message.success('操作成功')
      getList()
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

// 备注提交 -
const handleRemark = async (record: any) => {
  record.isRemarkShow = false
  let params = {
    id: record.id,
    remark: record.remark,
  }
  try {
    const { state, message: msg } = await xyApi.editRefundOrderRemark(params)
    if (state === 200) {
      message.success('备注保存成功')
      getList()
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

const EditRemarkSet = async (record: any) => {
  record.isRemarkShow = true
}

let okRobat = ref<string>()
const selectRobat = (selectValue: unknown) => {
  okRobat.value = selectValue as string
  searchParams.value.robotId = selectValue as string
  getList()
}
interface OptionList {
  label: string
  value: string
}
let optionList = ref<Array<OptionList>>([])
const getRobatList = async () => {
  try {
    let {
      state,
      data,
      message: msg,
    } = await accountApi.getFishRobotList({
      currentPage: 1,
      pageSize: 100,
    })
    if (state === 200) {
      optionList.value = data.list.map((item: any) => {
        return {
          label: item.nickName,
          value: item.id,
        }
      })
      optionList.value.unshift({
        label: '全部',
        value: '',
      })
      selectRobat(optionList.value[0].value)
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

const filterOption = (input: string, option: any) => {
  return option.label.indexOf(input) >= 0
}

onMounted(() => {
  getRobatList()
})

const advancedSearch = () => {
  searchDrawerRef.value.showDrawer()
}
</script>

<template>
  <!-- <page-container :title="route.meta.title"> -->
  <!-- <div style="background-color: #fff; margin-bottom: 15px; border-radius: 3px"> -->
  <!-- <PullXyRobot @selectRobot="selectRobot"></PullXyRobot> -->
  <!-- <span>平台账号：</span>
    <a-select
      v-model:value="okRobat"
      @change="selectRobat"
      placeholder="请选择"
      style="width: 150px; text-align: left"
      allowClear
      show-search
      :options="optionList"
      :filter-option="filterOption"
    >
      <a-select-option v-for="(item, index) in optionList" :key="index" :value="item.value">
        {{ item.label }}
      </a-select-option>
    </a-select>
  </div> -->

  <!-- <a-card style="overflow-x: scroll"> -->
  <div class="searchBox">
    <a-form ref="formRef" layout="inline" :model="formState" class="formClass">
      <!-- <a-form-item label="平台账号">
            <a-select
              v-model:value="okRobat"
              @change="selectRobat"
              placeholder="请选择"
              style="width: 150px; text-align: left"
              allowClear
              show-search
              :options="optionList"
              :filter-option="filterOption"
            >
              <a-select-option v-for="(item, index) in optionList" :key="index" :value="item.value">
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-item> -->

      <a-form-item>
        <div style="background-color: #fff; position: relative; bottom: -1px">
          <!-- <PullXyRobot @selectRobot="selectRobot"></PullXyRobot> -->
          <span>闲鱼账号：</span>
          <a-select
            v-model:value="okRobat"
            @change="selectRobat"
            placeholder="请选择"
            style="width: 200px; text-align: left"
            allowClear
            show-search
            :options="optionList"
            :filter-option="filterOption"
          >
            <a-select-option v-for="(item, index) in optionList" :key="index" :value="item.value">
              {{ item.label }}
            </a-select-option>
          </a-select>
        </div>
      </a-form-item>

      <a-form-item label="闲鱼订单号" name="orderNumber">
        <a-input
          v-model:value="formState.orderNumber"
          placeholder="闲鱼订单号"
          style="width: 200px"
        />
      </a-form-item>

      <a-form-item label="退款订单号" name="refundOrderNumber">
        <a-input
          v-model:value="formState.refundOrderNumber"
          placeholder="退款订单号"
          style="width: 200px"
        />
      </a-form-item>

      <SearchDrawer ref="searchDrawerRef">
        <div>
          <a-form-item label="闲鱼订单号" name="orderNumber">
            <a-input
              v-model:value="formState.orderNumber"
              placeholder="闲鱼订单号"
              style="width: 240px"
            />
          </a-form-item>

          <a-form-item label="退款订单号" name="refundOrderNumber">
            <a-input
              v-model:value="formState.refundOrderNumber"
              placeholder="退款订单号"
              style="width: 240px"
            />
          </a-form-item>

          <a-form-item label="买家昵称" name="fansNickName">
            <a-input
              v-model:value="formState.fansNickName"
              placeholder="买家昵称"
              style="width: 250px"
            />
          </a-form-item>

          <a-form-item label="订单状态" name="refundStatus">
            <a-select
              v-model:value="formState.refundStatus"
              placeholder="退款订单状态"
              style="width: 250px"
              allowClear
            >
              <a-select-option
                v-for="(item, index) in orderStatusList"
                :key="index"
                :value="item.value"
              >
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item style="text-align: right">
            <a-button type="primary" @click="search">搜索</a-button>
            <a-button @click="reset" style="margin-left: 10px">重置</a-button>
          </a-form-item>
        </div>
      </SearchDrawer>

      <a-form-item>
        <a-button type="primary" @click="search">搜索</a-button>
        <a-button @click="reset">重置</a-button>
        <a-button type="primary" @click="advancedSearch">高级搜索</a-button>
      </a-form-item>
    </a-form>
  </div>

  <a-alert
    description="小提示：只要鼠标在表格上，按住左Shift键并滚动鼠标滚轮就可以横向滚动表格"
    type="info"
    banner
    style="margin-bottom: 10px; padding: 10px"
  />

  <a-table
    style="overflow-x: scroll"
    :columns="columns"
    :data-source="dataSource"
    :pagination="pagination"
    :loading="loading"
    @change="changePage"
    rowKey="id"
    :scroll="{ x: 100 }"
    size="small"
  >
    <template #emptyText>
      <a-empty description="暂无数据" />
    </template>

    <template #headerCell="{ column }">
      <template v-if="column.key === 'id'">
        <span>id</span>
      </template>
    </template>

    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'orderNumber'">
        <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '120px' }">
          <a-descriptions-item label="闲鱼订单号">
            {{ record.orderNumber }}
            <a @click="copyToCliboard(record.orderNumber)"><CopyOutlined /></a>
          </a-descriptions-item>
          <a-descriptions-item label="退款订单号">
            {{ record.refundOrderNumber }}
            <a @click="copyToCliboard(record.refundOrderNumber)"><CopyOutlined /></a>
          </a-descriptions-item>
          <a-descriptions-item label="货物状态">
            <a-tag v-if="record.productStatus == 1" color="red">未收到货</a-tag>
            <a-tag v-if="record.productStatus == 2" color="blue">已收到货</a-tag>
            <a-tag v-if="record.productStatus == 3" color="blue">已寄回</a-tag>
            <a-tag v-if="record.productStatus == 4" color="red">未发货</a-tag>
            <a-tag v-if="record.productStatus == 5" color="blue">卖家确认收货</a-tag>
            <a-tag v-if="record.productStatus == 6" color="blue">已发货</a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="退款订单状态">
            <a-tooltip placement="top" v-if="record.refundStatus == 1">
              <template #title>
                <a-tag v-if="record.refundStatus == 1" color="blue">
                  买家已经申请退款，等待卖家同意
                </a-tag>
              </template>
              <div class="hiddenText">
                <a-tag v-if="record.refundStatus == 1" color="blue">
                  买家已经申请退款，等待卖家同意
                </a-tag>
              </div>
            </a-tooltip>

            <a-tooltip placement="top" v-if="record.refundStatus == 2">
              <template #title>
                <a-tag v-if="record.refundStatus == 2" color="blue">
                  卖家已经同意退款，等待买家退货
                </a-tag>
              </template>
              <div class="hiddenText">
                <a-tag v-if="record.refundStatus == 2" color="blue">
                  卖家已经同意退款，等待买家退货
                </a-tag>
              </div>
            </a-tooltip>

            <a-tooltip placement="top" v-if="record.refundStatus == 3">
              <template #title>
                <a-tag v-if="record.refundStatus == 3" color="blue">
                  买家已经退货，等待卖家确认收货
                </a-tag>
              </template>
              <div class="hiddenText">
                <a-tag v-if="record.refundStatus == 3" color="blue">
                  买家已经退货，等待卖家确认收货
                </a-tag>
              </div>
            </a-tooltip>

            <a-tag v-if="record.refundStatus == 4" color="red">退款关闭</a-tag>
            <a-tag v-if="record.refundStatus == 5" color="blue">退款成功</a-tag>
            <a-tag v-if="record.refundStatus == 6" color="red">卖家拒绝退款</a-tag>
            <a-tag v-if="record.refundStatus == 8" color="blue">等待卖家确认退货地址</a-tag>
            <a-tag v-if="record.refundStatus == 9" color="blue">没有申请退款</a-tag>
            <a-tag v-if="record.refundStatus == 11" color="blue">退款结束</a-tag>
            <a-tag v-if="record.refundStatus == 0" color="red">未知</a-tag>
          </a-descriptions-item>
        </a-descriptions>
      </template>

      <template v-else-if="column.key === 'productImg'">
        <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '120px' }">
          <a-descriptions-item label="宝贝标题">
            <a-tooltip placement="top">
              <template #title>
                <span>{{ record.productTitle }}</span>
              </template>
              <span class="hiddenText">{{ record.productTitle }}</span>
            </a-tooltip>
          </a-descriptions-item>
          <a-descriptions-item label="规格">
            <a-tooltip placement="top">
              <template #title>
                <span>{{ record.productSku }}</span>
              </template>
              <div class="hiddenText">{{ record.productSku }}</div>
            </a-tooltip>
          </a-descriptions-item>
          <a-descriptions-item label="店铺">
            <a-tooltip placement="top">
              <template #title>
                <span>{{ record.robotNickName }}</span>
              </template>
              <span class="hiddenText">{{ record.robotNickName }}</span>
            </a-tooltip>
          </a-descriptions-item>
          <a-descriptions-item label="宝贝图片">
            <a-popover placement="rightTop">
              <template #content>
                <div class="popoverImg">
                  <img :src="record.productImg" alt="" />
                </div>
              </template>
              <a>查看</a>
            </a-popover>
          </a-descriptions-item>
        </a-descriptions>
      </template>

      <template v-else-if="column.key === 'fansNickName'">
        <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '120px' }">
          <a-descriptions-item label="买家昵称">
            <a-tooltip placement="top">
              <template #title>
                <span>{{ record.fansNickName }}</span>
              </template>
              <span class="hiddenText">{{ record.fansNickName }}</span>
              <a @click="copyToCliboard(record.fansNickName)"><CopyOutlined /></a>
            </a-tooltip>
          </a-descriptions-item>
          <a-descriptions-item label="购买数量">{{ record.amount }}</a-descriptions-item>
          <a-descriptions-item label="申请退款金额">
            ￥{{ toYuan(record.applyRefundPrice) }}
          </a-descriptions-item>
          <a-descriptions-item label="实际退款金额">
            ￥{{ toYuan(record.refundPrice) }}
          </a-descriptions-item>
        </a-descriptions>
      </template>

      <template v-else-if="column.key === 'remark'">
        <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '150px' }">
          <a-descriptions-item label="备注">
            <a-tooltip placement="top" v-if="!record.isRemarkShow">
              <template #title>
                <span>{{ record.remark }}</span>
              </template>
              <span class="hiddenText">{{ record.remark }}</span>
            </a-tooltip>
            <a-input
              v-else
              v-model:value="record.remark"
              @blur="handleRemark(record)"
              style="border: 0"
            />
            <EditOutlined
              @click="EditRemarkSet(record)"
              v-if="!record.isRemarkShow"
              style="margin-left: 6px; color: #1890ff"
            />
          </a-descriptions-item>
          <a-descriptions-item label="申请退款原因">
            <a-tooltip placement="top">
              <template #title>
                <span>{{ record.refundReason }}</span>
              </template>
              <span class="hiddenText">{{ record.refundReason }}</span>
            </a-tooltip>
          </a-descriptions-item>
          <a-descriptions-item label="申请退款二级原因">
            <a-tooltip placement="top">
              <template #title>
                <span>{{ record.refundSubReason }}</span>
              </template>
              <span class="hiddenText">{{ record.refundSubReason }}</span>
            </a-tooltip>
          </a-descriptions-item>
          <a-descriptions-item label="买家是否需要退货">
            <a-tag color="blue" v-if="record.returnProductStatus == 0">仅退款</a-tag>
            <a-tag color="red" v-if="record.returnProductStatus == 1">退货退款</a-tag>
          </a-descriptions-item>
        </a-descriptions>
      </template>

      <template v-else-if="column.key === 'createTime'">
        <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '120px' }">
          <a-descriptions-item label="订单ID">
            {{ record.orderId }}
          </a-descriptions-item>
          <a-descriptions-item label="订单主状态">
            <a-tag color="red" v-if="record.orderStatus == '0'">未知状态</a-tag>
            <a-tag color="blue" v-if="record.orderStatus == '1'">已创建</a-tag>
            <a-tag color="blue" v-if="record.orderStatus == '2'">已付款</a-tag>
            <a-tag color="blue" v-if="record.orderStatus == '3'">已发货</a-tag>
            <a-tag color="blue" v-if="record.orderStatus == '4'">交易成功</a-tag>
            <a-tag color="red" v-if="record.orderStatus == '5'">已退款</a-tag>
            <a-tag color="blue" v-if="record.orderStatus == '6'">交易关闭</a-tag>
            <a-tag color="blue" v-if="record.orderStatus == '7'">退款中</a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="创建时间">
            {{ timeFormat_2(record.createTime) }}
          </a-descriptions-item>
          <a-descriptions-item label="修改时间">
            {{ timeFormat_2(record.updateTime) }}
          </a-descriptions-item>
        </a-descriptions>
      </template>

      <template v-else-if="column.key === 'action'">
        <div style="width: 180px">
          <!-- <a @click="refundMoney(record)">订单退款</a> -->
          <div>
            <a-popconfirm
              v-if="
                (record.refundStatus == 1 && record.returnProductStatus == 0) ||
                (record.refundStatus == 3 && record.returnProductStatus == 1)
              "
              title="确定同意？"
              ok-text="是"
              cancel-text="否"
              @confirm="okAgree(record.orderId, record.id)"
            >
              <a>同意退款并执行打款</a>
            </a-popconfirm>
            <a v-else style="color: gray">同意退款并执行打款</a>
          </div>
          <div>
            <a-popconfirm
              v-if="record.refundStatus == 1 && record.returnProductStatus == 1"
              title="确定同意？"
              ok-text="是"
              cancel-text="否"
              @confirm="okAgree_2(record.orderId, record.id)"
            >
              <a>同意退货并提供退货地址</a>
            </a-popconfirm>
            <a v-else style="color: gray">同意退货并提供退货地址</a>
          </div>
          <div>
            <a-popconfirm
              v-if="record.orderStatus == 3 && record.refundStatus == 1"
              title="确定拒绝？"
              ok-text="是"
              cancel-text="否"
              @confirm="nOAgree(record.orderId, record.id)"
            >
              <a>拒绝退款</a>
            </a-popconfirm>
            <a v-else style="color: gray">拒绝退款</a>
          </div>
        </div>
      </template>
    </template>
  </a-table>
  <!-- </a-card> -->
  <RefundModal ref="refundModalRef"></RefundModal>
  <!-- </page-container> -->
</template>

<style lang="less" scoped>
.hiddenText {
  display: inline-block;
  max-width: 140px;
  overflow: hidden;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  line-height: 16px;
}

.aTag-seatNo:nth-child(n + 2) {
  margin-top: 3px;
}

.formClass {
  :nth-child(1) {
    // margin-bottom: 2px;
  }
}

.searchBox {
  margin-bottom: 10px;
  display: flex;

  input {
    width: 200px;
    margin-right: 10px;
  }

  button {
    margin-right: 10px;
  }
}

a:hover {
  color: red;
}

.imgBox {
  width: 50px;
  height: 50px;

  img {
    height: 50px;
  }
}

.popoverImg {
  width: 300px;
  img {
    width: 100%;
  }
}

.robitStatusClass {
  text-align: center;
}
</style>
